package com.github.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.bean.ServerUser;
import com.github.bean.ServerUserSession;
import com.github.common.constant.MyConstant;
import com.github.manager.Manager;
import com.github.util.Role;
import com.github.util.SessionSocketHolder;
import com.github.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class Handshake implements HandshakeInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public Handshake(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String query = request.getURI().getQuery();
        String device_type = Utils.getParamValue(query, "device_type");
        String account = Utils.getParamValue(query, "account");
        ServerUserSession serverUserSession = SessionSocketHolder.get(account, Role.SERVER);
        if (serverUserSession == null) {
            return true;
        }
        ServerUserSession otherUserSession = SessionSocketHolder.get(account, device_type);
        if (SessionSocketHolder.isOpen(otherUserSession)) {
            response.setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
            return false;
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
